﻿using Microsoft.Extensions.Hosting;
using SuperSocket;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xc.DataAccess.Protocoals.WaterMeters.Models;
using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;

namespace Xc.DataAccess.Protocoals.WaterMeters.Services
{
    public class WaterMeterSocketService : IWaterMeterSocketService
    {
        /// <summary>
        /// 表具操作服务
        /// </summary>
        public IMeterHandleService MeterHandleService { get; private set; }
        private IHost host;
        public WaterMeterSocketService()
        {


        }
        public WaterMeterSocketService(IMeterHandleService packageHandlerService)
        {
            this.MeterHandleService = packageHandlerService;
        }

        public void Option(ListenOptions listener)
        {
            if (host != null)
            {
                host.StopAsync();
                host = null;
            }
           var  _superSocketHostBuilder = SuperSocketHostBuilder.Create<MeterFrameRx, MeterFramePipleFilter>();
            _superSocketHostBuilder.UseHostedService<MeterService<MeterFrameRx>>();
            _superSocketHostBuilder.UseSession<DevcieInfoAppSession>();
            _superSocketHostBuilder.ConfigureLogging((h, builder) =>
            {
                builder.AddConsole().AddDebug();
            });
            _superSocketHostBuilder.ConfigureSuperSocket((options) =>
            {
                options.AddListener(listener);
            });
            _superSocketHostBuilder.UsePackageHandler((session1, frame) => MeterHandleService.PackageHandle((IDevcieInfoAppSession)session1, frame), (session1, han) => MeterHandleService.ErrorHanle((IDevcieInfoAppSession)session1, han));
            _superSocketHostBuilder.UseSessionHandler(session => MeterHandleService.OnConnect((IDevcieInfoAppSession)session), (sessionOffline, e) => MeterHandleService.OnClose((IDevcieInfoAppSession)sessionOffline, e));
           // _superSocketHostBuilder.UseUdp();
            host = _superSocketHostBuilder.Build();
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <returns></returns>
        public async Task Start()
        {
            await host.StartAsync();
        }
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <returns></returns>
        public async Task Stop()
        {
            await host.StopAsync();
        }
    }
}
